<template>
    <view class="my-input-captche-field">
        <u--input v-model="localValue" :placeholder="placeholder" :disabled="disabled" :readonly="readonly"
            :clearable="clearable" :maxlength="maxlength" :fontSize="fontSize" @input="input" @change="change"
            border="none" />
        <img class="img" :src="'data:image/png;base64,' + codeImg" @click="getRandomImage" />
    </view>
</template>

<script>
    import fetch from '@/utils/fetch';

    export default {
        name: 'InputCaptcheField',
        props: {
            value: String,
            placeholder: {
                type: String,
                default: '请输入验证码'
            },
            disabled: {
                type: Boolean,
                default: false
            },
            readonly: {
                type: Boolean,
                default: false
            },
            clearable: {
                type: Boolean,
                default: false
            },
            maxlength: {
                type: Number,
                default: 6
            },
            fontSize: {
                type: String,
                default: '2rem'
            },
            uuid: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                localValue: '',
                codeImg: ''
            }
        },
        methods: {
            input(value) {
                this.$emit('input', value);
            },
            change(value) {
                this.$emit('change', value);
            },
            getRandomImage() {
                fetch('get', '/basic/captchaImage', {}, {}, '验证码获取异常', false).then(res => {
                    this.codeImg = res.img;
                    this.$emit('generateUUID', res.uuid);
                })
            },
            reset(){
                this.localValue = '';
                this.getRandomImage();
                this.$emit('input', this.localValue);
            }
        },
        mounted() {
            this.localValue = this.value;
            this.getRandomImage();
        }
    };
</script>

<style lang="scss" scoped>
    .my-input-captche-field {
        height: 8rem;
        width: 100%;
        position: relative;

        .u-input {
            height: 100%;
            border: 1px solid #ccc;
            border-radius: 1rem;
            padding: 0 2rem !important;
        }

        .img {
            position: absolute;
            width: 15rem;
            height: 5.5rem;
            right: 1.2rem;
            top: 1.2rem;
            border-radius: 1rem;
        }
    }
</style>